'use strict';

const Controller = require('egg').Controller;
var qr = require('qr-image');

class MycouponsController extends Controller {
    
    

    
    // 核销 数据
    async qrcodelist() {
        const { ctx, app } = this
        const wxUser = ctx.wxUser
        ctx.validate({
            id: {
                type: 'int',
                required: true,
                desc: '券id'
            }
        })
        const { id } = ctx.request.body
        let listOne = await app.model.MyCoupons.findOne({
            where: {
                wx_user_id: wxUser.id,
                id,
                status: '2'
            },
            include: [
                {
                    model: app.model.Coupons,
                    as: 'coupons'
                }
            ]
        })
        // 验证券是否存在
        if (!listOne) {
            ctx.throw(400, '券不存在')
        }
        // 验证券是否过期
        let newTime = parseInt((new Date().getTime()) / 1000)
        if (listOne.coupons.fixed_days == 0) {//固定使用期
            if (listOne.coupons.fixed_end_time < newTime) {
                ctx.throw(400, '已过期')
            }
        } else {//购买时间后 好多天有效
            let endTime = (listOne.coupons.fixed_days * 24 * 60 * 60) + listOne.pay_time
            if (endTime < newTime) {
                ctx.throw(400, '已过期!')
            }
        }
        ctx.apiSuccess(listOne)
    }
    // 分享 小程序 二维码
    async wxqrcode() {
        const { ctx, app, service } = this
        const wxUser = ctx.wxUser
        ctx.validate({
            id: {
                type: 'int',
                required: true,
                desc: '券id'
            }
        })
        const { id } = ctx.request.body
        let listOne = await app.model.MyCoupons.findOne({
            where: {
                wx_user_id: wxUser.id,
                id,
                status: '2'
            },
            include: [
                {
                    model: app.model.Coupons,
                    as: 'coupons'
                }
            ]
        })
        // 验证券是否存在
        if (!listOne) {
            ctx.throw(400, '券不存在')
        }
        // 验证券是否过期
        let newTime = parseInt((new Date().getTime()) / 1000)
        if (listOne.coupons.fixed_days == 0) {//固定使用期
            if (listOne.coupons.fixed_end_time < newTime) {
                ctx.throw(400, '已过期')
            }
        } else {//购买时间后 好多天有效
            let endTime = (listOne.coupons.fixed_days * 24 * 60 * 60) + listOne.pay_time
            if (endTime < newTime) {
                ctx.throw(400, '已过期!')
            }
        }
        delete listOne.coupons
        let access_token = await service.utils.getAccessToken()
        let url = `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${access_token}&scene='aaa'`
        let uaa = await ctx.curl(url)
        ctx.apiSuccess(uaa.data)
    }

    
}

module.exports = MycouponsController;
